package _interview100;

import _object.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 */
public class No105 {
    private int[] preorder;
    private int preLen, preIndex;
    private Map<Integer, Integer> inorderMap;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        this.preLen = preorder.length;
        this.preIndex = 0;
        inorderMap = new HashMap<>();

        for (int i = 0; i < inorder.length; i++) {
            inorderMap.put(inorder[i], i);
        }
        return dfs(0, inorder.length - 1);
    }

    private TreeNode dfs(int left, int right) {
        if (left > right || preIndex >= preLen) return null;
        TreeNode node = new TreeNode(preorder[preIndex]);
        int mid = inorderMap.get(preorder[preIndex]);
        preIndex++;
        node.left = dfs(left, mid - 1);
        node.right = dfs(mid + 1, right);
        return node;
    }
}
